import threading
from flask import render_template, flash, redirect, url_for, request
from . import sentiment
from flask.ext.login import login_required
from app.dionice_repository import clean_refresh_dionice, update_dionice
from app.sentiment.forms import ReloadButton, UpdateButton

thrRefresh = threading.Thread(target=clean_refresh_dionice)
thrUpdate = threading.Thread(target=update_dionice)

@sentiment.route('/', methods=['GET'])
@login_required
def index():
    return render_template('sentiment/index.html', update_form=UpdateButton(), reload_form=ReloadButton())

@sentiment.route('/reload', methods=['POST'])
@login_required
def reload():
    form = ReloadButton(request.form)
    if request.method == 'POST':
        if not thrRefresh.is_alive() or thrUpdate.is_alive():
            thrRefresh.start()
    return redirect(url_for('sentiment.index'))

@sentiment.route('/update', methods=['POST'])
@login_required
def update():
    form = UpdateButton(request.form)
    if request.method == 'POST':
        if not thrRefresh.is_alive() or thrUpdate.is_alive():
            thrUpdate.start()
    return redirect(url_for('sentiment.index'))